package com.qidian.mespro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mespro.mapper.ProductOrderMapper;
import com.qidian.mespro.service.ProductOrderService;
import com.qidianit.mes.pojo.ProductOrder;
import com.qidianit.mes.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @ author: 周晓轩
 * @ company 起点编程
 * @ time: 2025/9/20 - 15:00
 * @ Description:
 */
@Service
public class ProductOrderServiceImpl implements ProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Override
    public Result<PageInfo<ProductOrder>> productOrderList(ProductOrder order, String materialName, Integer status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductOrder> productOrderList = productOrderMapper.productOrderList(order, materialName, status);
        return Result.success(new PageInfo<>(productOrderList));
    }

    @Override
    public Result<ProductOrder> getProductionOrderById(Long id) {
        ProductOrder order = productOrderMapper.selectById(id);
        if (order == null) {
            return Result.error("工单不存在");
        }
        return Result.success(order);
    }

    @Override
    public Result<ProductOrder> addProductionOrder(ProductOrder productOrder) {
        // 处理库存备货时的客户信息
        handleStockPreparationCustomerInfo(productOrder);
        if (productOrder.getProductionOrderCode() == null || productOrder.getProductionOrderCode().trim().isEmpty()) {
            return Result.error("工单编号不能为空");
        }

        int count = productOrderMapper.countByCode(productOrder.getProductionOrderCode());
        if (count > 0) {
            return Result.error("已存在编号为[" + productOrder.getProductionOrderCode() + "]的工单，请更换编号");
        }

        return productOrderMapper.insertProductionOrder(productOrder) == 1 ? Result.success(productOrder) : Result.error("保存失败");
    }

    @Override
    public Result updateProductOrder(ProductOrder productOrder) {
        // 处理库存备货时的客户信息
        handleStockPreparationCustomerInfo(productOrder);
        ProductOrder existingOrder = productOrderMapper.selectById(productOrder.getId());
        if (existingOrder == null) {
            return Result.error("工单不存在");
        }
        if (!existingOrder.getProductionOrderCode().equals(productOrder.getProductionOrderCode())) {
            int count = productOrderMapper.countByCode(productOrder.getProductionOrderCode());
            if (count > 0) {
                return Result.error("工单编号重复");
            }
        }
        int number = productOrderMapper.updateProductionOrder(productOrder);
        return  number == 1 ? Result.success() : Result.error("编辑失败");
    }

    @Override
    public Result deleteProductOrderById(Long id) {
        return productOrderMapper.deleteProductOrderById(id) == 1 ? Result.success() : Result.error("删除失败");
    }

    @Override
    public Result<String> confirmProductionOrder(Long id, Long updatorId) {
        ProductOrder order = productOrderMapper.selectById(id);
        if (order == null) {
            return Result.error("工单不存在");
        }
        int rows = productOrderMapper.updateProductionOrderStatus(id, 2L, "确认提交待审核", updatorId);
        return rows == 1 ? Result.success("确认工单成功") : Result.error("确认工单失败");
    }

    @Override
    public Result<String> auditProductionOrder(Long id, Integer auditResult, String auditOpinion, Long updatorId) {
        ProductOrder order = productOrderMapper.selectById(id);
        if (order == null) {
            return Result.error("工单不存在");
        }

        // 状态映射：1-通过（3），0-不通过（1）
        Long status = auditResult == 1 ? 3L : 1L;
        String msg = auditResult == 1 ? "审核通过成功" : "审核不通过，工单回退至草稿状态";

        // 传入updatorId参数
        int rows = productOrderMapper.updateProductionOrderStatus(id, status, auditOpinion, updatorId);
        return rows == 1 ? Result.success(msg) : Result.error("审核工单失败");
    }

    @Override
    public Result<String> getAutoCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        // 这里可以从数据库查询当前日期最大的编号，然后递增，直接生成固定格式
        String autoCode = "PROD-" + dateStr + "-" + String.format("%04d", new Random().nextInt(10000));
        return Result.success(autoCode);
    }

    /**
     * 处理库存备货类型工单的客户信息，强制设为null
     */
    private void handleStockPreparationCustomerInfo(ProductOrder productOrder) {
        if (productOrder.getProductionOrderSource() != null && productOrder.getProductionOrderSource() == 2) {
            productOrder.setCustomerCode(null);
            productOrder.setCustomerName(null);
            productOrder.setCustomer(null);
        }
    }
}
